package org.rain.core.scope;

import jakarta.servlet.ServletException;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * created by yangtong on 2025/4/11 13:21:07
 * <br/>
 */
public class InvocationChain {

    List<ScopeInvocation> invocations;
    ServletTask task;
    private int count = 1;

    public InvocationChain(List<ScopeInvocation> invocations) {
        if (invocations == null) {
            invocations = Collections.emptyList();
        }
        this.invocations = invocations;
    }

    public InvocationChain withTask(ServletTask task) {
        this.task = task;
        return this;
    }

    public void doChain() throws ServletException, IOException {
        if (count > invocations.size()) {
            if (task != null) {
                task.doTask();
                return;
            }
        }
        ScopeInvocation scopeInvocation = invocations.get(count++ - 1);
        scopeInvocation.doNext(this, null, null);
    }

}
